<?php


/**
 * websocket服务
 */
class Ws
{
	private $url = '0.0.0.0';
	private $port = '50271';
	public $ws = null;

	public function __construct($url = '',$port = ''){
		if(!empty($url))$this->url = $url;
		if(!empty($port))$this->port = $port;
	}

	public function createWs(){
		$this->ws = new Swoole\WebSocket\Server($this->url,$this->port);

		$this->ws->set([
			'worker_num'=>2,
			'task_worker_num'=>2
		]);

		$this->ws->on('open',[$this,'openHandler']);
		$this->ws->on('message',[$this,'messageHandler']);
		$this->ws->on('task',[$this,'taskBegainHandler']);
		$this->ws->on('finish',[$this,'taskFinishHandler']);
		$this->ws->on('close',[$this,'closeHandler']);
		$this->ws->start();
	}

	/*
	监听WebSocket连接打开事件处理函数
	*/
	public function openHandler($ws, $request) {
		echo "客户端{$request->fd}上线\n";
	}


	/*
	监听WebSocket消息事件处理函数
	*/
	public function messageHandler($ws, $frame) {
	    echo "客户端{$frame->fd}说:{$frame->data}\n";

	    //投递任务
	    $ws->task(['task'=>1,'fd'=>$frame->fd]);

	    echo "我说:你好客户端\n";
	    $ws->push($frame->fd, "你好客户端");
	}


	/*
	投递任务事件处理函数
	@$server 
	@task_id 任务ID，由swoole扩展内自动生成，用于区分不同的任务
	@worker_id 来自于哪个worker进程
	@$data 是任务的内容
	*/
	public function taskBegainHandler($server,$task_id,$worker_id,$data){
		echo json_encode($data)."\n";
		sleep(10);
		return '完成';
	}

	/*
	投递任务事件结束处理函数
	@$task_id 任务ID，由swoole扩展内自动生成，用于区分不同的任务
	@data 投递任务事件处理函数返回值
	*/
	public function taskFinishHandler($server,$task_id,$data){
		echo "task任务处理状态：{$data}\n";
	}

	//监听WebSocket连接关闭事件
	public function closeHandler($ws, $fd) {
	    echo "客户端{$fd}下线\n";
	}

}

(new Ws())->createWs();